package com.inspectortime.webapp.inspector.fee;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import com.inspectortime.domain.InspectorCompany;
import com.inspectortime.repository.Repository;
import com.inspectortime.webapp.util.HttpSessionUtils;

public class FeeWizardSqFtController implements Controller {

	private Repository repository;

	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		// GET
		if (request.getMethod().equalsIgnoreCase("get")) {
			InspectorCompany company = HttpSessionUtils.retrieveLoggedInCompany(request, repository);
			FeeWizardSqFtHelper helper = new FeeWizardSqFtHelper(company.getBaseInspectionFee());
			helper.populateFromCalculators(company);
			helper.sortEntries();
			FeeUtils.storeSqFtFeeWizardInSession(request, helper);

			ModelAndView mv = new ModelAndView("inspector/fee/feeWizardSqFt");
			mv.addObject("helper", helper);
			return mv;
		}
		
		// Result of a POST
		FeeWizardSqFtHelper helper = FeeUtils.retrieveSqFtFeeWizardHelperFromSession(request);

		// Bind and validate
		double amount = 0;
		BindException errors = new BindException(helper, "helper");
		for (String fieldName : helper.getSqFtRangeFees().keySet()) {
			String parameterName = "sqFtRangeFees[" + fieldName + "]";
			String value = request.getParameter(parameterName);
			if (value == null) {
				throw new RuntimeException("Missing parameter: " + parameterName);
			}			
			try {
				amount = Double.parseDouble(value);
			} catch (NumberFormatException e) {
				String label = helper.getSqFtRangeLabel(fieldName);
				String[] errorArgs = new String[] {label};
				errors.rejectValue(parameterName, "Invalid", errorArgs, label + ": Invalid value. Enter numbers only with no periods, spaces, or dollar signs");
			}		
			
			// Bind
			helper.setPrice(fieldName, amount);
		}
		
		if (errors.getErrorCount() > 0) {
			ModelAndView mv = new ModelAndView("inspector/fee/feeWizardSqFt", errors.getModel());			
			mv.addObject("helper", helper);
			mv.addObject("errors", errors);
			return mv;
		}

		// Success
		String viewName = "feeWizardAdjusters.html";
		ModelAndView mv = new ModelAndView("redirect:" + viewName);
		return mv;
		
	}

	public void setRepository(Repository repository) {
		this.repository = repository;
	}

}
